package lwjgl.engine;


import java.io.IOException;
import java.nio.FloatBuffer;

import org.lwjgl.BufferUtils;

import datastructures.Vector2f;

public abstract class Sprite extends Thread {

	Game g;
	
	private Texture texture;
	private Vector2f position;
	private float rotation;
	private boolean toBeKilled=false;
	private FloatBuffer fb_verts;
	private FloatBuffer fb_cols;
	
	public Sprite(Game g, String ref)
	{
		super(g.sprites_tg,ref);
		try
		{
			this.g = g;
			this.texture = TextureLoader.getTexture(ref);
			this.start();
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
			System.out.println("Error, Could not create Sprite");
			return;
		}
		
		float[] verts = {
				0.0f, 0.0f,
				0.0f, texture.getImageHeight(),
				texture.getImageWidth(), texture.getImageHeight(),
				texture.getImageWidth(), 0.0f,
		};
		
		float[] cols = {
				1.0f,1.0f,1.0f,1.0f,
				1.0f,1.0f,1.0f,1.0f,
				1.0f,1.0f,1.0f,1.0f,
				1.0f,1.0f,1.0f,1.0f,
		};		
			
		fb_verts = BufferUtils.createFloatBuffer(verts.length);
		fb_verts.put(verts);
		fb_cols = BufferUtils.createFloatBuffer(cols.length);
		fb_cols.put(cols);	
		
	}
	
	public FloatBuffer getFb_verts() {
		return fb_verts;
	}

	public FloatBuffer getFb_cols() {
		return fb_cols;
	}

	public int getWidth()
	{
		return texture.getImageWidth();
	}
	
	public int getHeight()
	{
		return texture.getImageHeight();
	}
	
	public Vector2f getPosition()
	{
		return this.position;
	}
	
	public float getRotation()
	{
		return this.rotation;
	}
	
	public Texture getTexture()
	{
		return this.texture;
	}
	
	public void kill()
	{
		this.toBeKilled = true;
	}
	
	protected abstract void update(long gametime);
	
	public void run()
	{
		long gametime = Game.getTime();
		long oldtime = Game.getTime();
		
		while(!toBeKilled)
		{
			gametime = Game.getTime() - oldtime;
			oldtime = Game.getTime();
			this.update(gametime);
			//TODO umbau, dass das game den sprite zeichnet
			//g.drawSprite(texture, position, rotation);
		}
	}
}
